package com.baixiaowen.xiaoaointerview.大厂笔试_白板面试篇.容器_集合_映射;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

/**
 * 实现LRU缓存 - 最近最少使用 使用LinkedHashMap实现
 *
 * @author Baixiaowen
 */
public class LRUCache<K, V> implements Iterable{

    int MAX = 3;
    LinkedHashMap<K, V> cache = new LinkedHashMap<>();

    public void cache(K key, V value) {
        if (cache.containsKey(key)) {
            cache.remove(key);
        } else if (cache.size() >= MAX) {
            // 如果元素个数超过最大值，删除第一个元素的Key，重新插入新元素
            Iterator it = cache.keySet().iterator();
            K first = (K) it.next();
            cache.remove(first);
        }
        cache.put(key, value);
    }

    @Override
    public Iterator iterator() {

        Iterator<K> it = cache.keySet().iterator();
        return new Iterator<K>() {
            @Override
            public boolean hasNext() {
                return it.hasNext();
            }

            @Override
            public K next() {
                return it.next();
            }
        };
    }

    public static void main(String[] args) {
        LRUCache<String, Integer> lru = new LRUCache<>();
        lru.cache("A", 1);
        lru.cache("B", 2);
        lru.cache("C", 3);

        lru.cache("D", 4);
        lru.cache("C", 10);
        System.err.println(
                "level <-" +
                StreamSupport.stream(lru.spliterator(), false)
                            .map(x -> x.toString())
                .collect(Collectors.joining("<-"))
        );
    }

}
